<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 3/30/17
 * Time: 2:38 PM
 */

namespace common\components\tools;


use yii\base\ErrorException;
use yii\log\Logger;

class Tools
{
    public static function objectToArray($obj)
    {
        $arr = is_object($obj) ? get_object_vars($obj) : $obj;
        if (is_array($arr)) {
            return array_map(__METHOD__, $arr);
        } else {
            return $arr;
        }
    }

    public static function arrayToObject($arr)
    {
        if (is_array($arr)) {
            return (object)array_map(__METHOD__, $arr);
        } else {
            return $arr;
        }
    }

    public static function makeModelGetErrorsToStringAndGetIt($errors)
    {
        $error_str = '';
        foreach ($errors->getErrors() as $k => $v) {
            $error_str .= $v[0];
        }
        return $error_str;
    }

    /**
     * 调试输出|调试模式下
     * @param  mixed $test 调试变量
     * @param  int $style 模式
     * @param  int $stop 是否停止
     * @return void       浏览器输出
     * @author wodrow <wodrow451611cv@gmail.com | 1173957281@qq.com>
     */
    public static function _vp($test, $stop = 0, $style = 0)
    {
        $outDir = \Yii::getAlias('@runtime');
        switch ($style) {
            case 0:
                echo "<pre>";
                echo "<br><hr>";
                var_dump($test);
                echo "</pre>";
                break;
            case 1:
                echo "<pre>";
                echo "<br><hr>";
                var_dump($test);
                echo "<hr/>";
                for ($i = 0; $i < 100; $i++) {
                    echo $i . "<hr/>";
                }
                echo "</pre>";
                break;
            case 2:
                file_put_contents($outDir . '/OUT.md', "\r" . var_export($test, true));
                break;
            case 3:
                file_put_contents($outDir . '/OUT.md', "\r\r" . var_export($test, true), FILE_APPEND);
                break;
        }
        if ($stop != 0) {
            exit("<hr/>");
        }
    }

    public static function log($msg, $log_name = "app")
    {
        $log = New \yii\log\FileTarget();
        $log->logFile = \Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . "logs" . DIRECTORY_SEPARATOR . "{$log_name}.log";
        $log->messages[] = [$msg, Logger::LEVEL_INFO, 'tool-log', time()];
        $log->export();
    }

    public static function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
//			var_dump($aStatus);
            return $sContent;
        } else {
            return false;
        }
    }

    public static function getOutCache($data)
    {
        ob_start();
        var_dump($data);
        $x = ob_get_contents();
        ob_end_clean();
        return $x;
    }

    public static function html2word($html, $path)
    {
        ob_start();
        echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"
        xmlns:w="urn:schemas-microsoft-com:office:word"
        xmlns="http://www.w3.org/TR/REC-html40">';
        echo $html;
        echo "</html>";
        $data = ob_get_contents();
        ob_end_clean();
        $fp = fopen($path, "w+");
        fwrite($fp, $data);
        fclose($fp);
    }

    /**
     * 根据HTML代码获取word文档内容
     * 创建一个本质为mht的文档，该函数会分析文件内容并从远程下载页面中的图片资源
     * 该函数依赖于类MhtFileMaker
     * 该函数会分析img标签，提取src的属性值。但是，src的属性值必须被引号包围，否则不能提取
     *
     * @param string $content HTML内容
     * @param string $absolutePath 网页的绝对路径。如果HTML内容里的图片路径为相对路径，那么就需要填写这个参数，来让该函数自动填补成绝对路径。这个参数最后需要以/结束
     * @param bool $isEraseLink 是否去掉HTML内容中的链接
     * by www.jbxue.com
     */
    public static function getWordDocument($content, $absolutePath = "", $isEraseLink = true)
    {
        /*$content = $this->render('test');
        $fileContent = Tools::getWordDocument($content, "http://192.168.1.102:9112/");
        $fp = fopen(\Yii::getAlias('@runtime')."/test.docx", 'w');
        fwrite($fp, $fileContent);
        fclose($fp);*/
        $mht = new MhtFileMaker();
        if ($isEraseLink)
            $content = preg_replace('/<a\s*.*?\s*>(\s*.*?\s*)<\/a>/i', '$1', $content);   //去掉链接

        $images = array();
        $files = array();
        $matches = array();
        //这个算法要求src后的属性值必须使用引号括起来
        if (preg_match_all('/<img[.\n]*?src\s*?=\s*?[\"\'](.*?)[\"\'](.*?)\/>/i', $content, $matches)) {
            $arrPath = $matches[1];
            for ($i = 0; $i < count($arrPath); $i++) {
                $path = $arrPath[$i];
                $imgPath = trim($path);
                if ($imgPath != "") {
                    $files[] = $imgPath;
                    if (substr($imgPath, 0, 7) == 'http://') {
                        //绝对链接，不加前缀
                    } else {
                        $imgPath = $absolutePath . $imgPath;
                    }
                    $images[] = $imgPath;
                }
            }
        }
        $mht->AddContents("tmp.html", $mht->GetMimeType("tmp.html"), $content);

        for ($i = 0; $i < count($images); $i++) {
            $image = $images[$i];
            if (@fopen($image, 'r')) {
                $imgcontent = @file_get_contents($image);
                if ($content)
                    $mht->AddContents($files[$i], $mht->GetMimeType($image), $imgcontent);
            } else {
                echo "file:" . $image . " not exist!<br />";
            }
        }

        return $mht->GetFile();
    }

    /**
     * php获取文件名
     * @param $url
     * @return mixed
     */
    public static function retrieve($url)
    {
        preg_match('/\/([^\/]+\.[a-zA-Z]+)[^\/]*$/', $url, $match);
        return $match[1];
    }

    /**
     * php获取文件扩展名
     * @param $url
     * @return mixed
     */
    public static function getExt($url)
    {
        $path = parse_url($url);
        $str = explode('.', $path['path']);
        return $str[1];
    }

    public static function download($file_url, $new_name = '')
    {
        if (!isset($file_url) || trim($file_url) == '') {
            return '500';
        }
        if (!file_exists($file_url)) { //检查文件是否存在
            return '404';
        }
        $file_name = basename($file_url);
        $file_type = explode('.', $file_url);
        $file_type = $file_type[count($file_type) - 1];
        $file_name = trim($new_name == '') ? $file_name : urlencode($new_name);
        $file_type = fopen($file_url, 'r'); //打开文件
//输入文件标签
        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length: " . filesize($file_url));
        header("Content-Disposition: attachment; filename=" . $file_name);
//输出文件内容
        echo fread($file_type, filesize($file_url));
        fclose($file_type);
    }

    /**
     * @param $filename 文件名（含路径）
     */
    public static function downloadFile($filename)
    {
        if (!file_exists($filename)) {
            exit("无法找到文件"); //即使创建，仍有可能失败。。。。
        }
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: ' . filesize($filename)); //告诉浏览器，文件大小
        @readfile($filename);
    }

    public static function strToHex($string)//字符串转十六进制
    {
        $hex = "";
        for ($i = 0; $i < strlen($string); $i++)
            $hex .= dechex(ord($string[$i]));
        $hex = strtoupper($hex);
        return $hex;
    }

    public static function hexToStr($hex)//十六进制转字符串
    {
        $string = "";
        for ($i = 0; $i < strlen($hex) - 1; $i += 2)
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        return $string;

    }

    public static function getBytes($string)
    {
        $bytes = array();
        for ($i = 0; $i < strlen($string); $i++) {
            $bytes[] = ord($string[$i]);
        }
        return $bytes;
    }

    public static function asc2bin($temp)
    {
        $data = '';
        $len = strlen($temp);
        for ($i = 0; $i < $len; $i++) $data .= sprintf("%08b", ord(substr($temp, $i, 1)));
        return $data;
    }

    /**
     *
     * ASCII 转 十六进制 以及 十六进制 转 ASCII
     * 非盈利组织或个人请放心转载，商业用途请征得作者同意
     *
     */
    //ASCII 转 十六进制
    public static function asc2hex($str)
    {
        return '\x' . substr(chunk_split(bin2hex($str), 2, '\x'), 0, -2);
    }

    //十六进制 转 ASCII
    public static function hex2asc($str)
    {
        $data = '';
        $str = join('', explode('\x', $str));
        $len = strlen($str);
        for ($i = 0; $i < $len; $i += 2) $data .= chr(hexdec(substr($str, $i, 2)));
        return $data;
    }

    /**
     * 转换一个String字符串为byte数组(10进制)
     * @param $str 需要转换的字符串
     * @param $bytes 目标byte数组
     * @author Zikie
     */

    public static function getBytes_10($str)
    {


        $len = strlen($str);
        $bytes = array();
        for ($i = 0; $i < $len; $i++) {
            if (ord($str[$i]) >= 128) {
                $byte = ord($str[$i]) - 256;
            } else {
                $byte = ord($str[$i]);
            }
            $bytes[] = $byte;
        }
        return $bytes;
    }


    /**
     * 转换一个String字符串为byte数组(16进制)
     * @param $str 需要转换的字符串
     * @param $bytes 目标byte数组
     * @author Zikie
     */

    public static function getBytes_16($str)
    {


        $len = strlen($str);
        $bytes = array();
        for ($i = 0; $i < $len; $i++) {
            if (ord($str[$i]) >= 128) {
                $byte = ord($str[$i]) - 256;
            } else {
                $byte = ord($str[$i]);
            }
            $bytes[] = "0x" . dechex($byte);
        }
        return $bytes;
    }


    /**
     * 转换一个String字符串为byte数组(2进制)
     * @param $str 需要转换的字符串
     * @param $bytes 目标byte数组
     * @author Zikie
     */

    public static function StrToBin($str)
    {
        //1.列出每个字符
        $arr = preg_split('/(?<!^)(?!$)/u', $str);
        //2.unpack字符
        foreach ($arr as &$v) {
            $temp = unpack('H*', $v);
            $v = base_convert($temp[1], 16, 2);
            unset($temp);
        }

        return $arr;
    }


    /**
     * 转换一个byte数组为String(2进制)
     * @param $str 需要转换的字符串
     * @param $bytes 目标byte数组
     * @author Zikie
     */

    function BinToStr($str)
    {
        $arr = explode(' ', $str);
        foreach ($arr as &$v) {
            $v = pack("H" . strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16));
        }

        return $v;
    }

    /**
     * 将字节数组转化为String类型的数据
     * @param $bytes 字节数组
     * @param $str 目标字符串
     * @return 一个String类型的数据
     */

    public static function toStr($bytes)
    {
        $str = '';
        foreach ($bytes as $ch) {
            $str .= chr($ch);
        }


        return $str;
    }

    /**
     * 转换一个int为byte数组
     * @param $byt 目标byte数组
     * @param $val 需要转换的字符串
     * @author Zikie
     */

    public static function integerToBytes($val)
    {
        $byt = array();
        $byt[0] = ($val & 0xff);
        $byt[1] = ($val >> 8 & 0xff);
        $byt[2] = ($val >> 16 & 0xff);
        $byt[3] = ($val >> 24 & 0xff);
        return $byt;
    }

    /**
     * 从字节数组中指定的位置读取一个Integer类型的数据
     * @param $bytes 字节数组
     * @param $position 指定的开始位置
     * @return 一个Integer类型的数据
     */

    public static function bytesToInteger($bytes, $position)
    {
        $val = 0;
        $val = $bytes[$position + 3] & 0xff;
        $val <<= 8;
        $val |= $bytes[$position + 2] & 0xff;
        $val <<= 8;
        $val |= $bytes[$position + 1] & 0xff;
        $val <<= 8;
        $val |= $bytes[$position] & 0xff;
        return $val;
    }


    /**
     * 转换一个shor字符串为byte数组
     * @param $byt 目标byte数组
     * @param $val 需要转换的字符串
     * @author Zikie
     */

    public static function shortToBytes($val)
    {
        $byt = array();
        $byt[0] = ($val & 0xff);
        $byt[1] = ($val >> 8 & 0xff);
        return $byt;
    }

    /**
     * 从字节数组中指定的位置读取一个Short类型的数据。
     * @param $bytes 字节数组
     * @param $position 指定的开始位置
     * @return 一个Short类型的数据
     */

    public static function bytesToShort($bytes, $position)
    {
        $val = 0;
        $val = $bytes[$position + 1] & 0xFF;
        $val = $val << 8;
        $val |= $bytes[$position] & 0xFF;
        return $val;
    }

    /**
     * 字符串转换为数组，主要用于把分隔符调整到第二个参数
     * @param  string $str 要分割的字符串
     * @param  string $glue 分割符
     * @return array
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public static function str2arr($str, $glue = ',')
    {
        return explode($glue, $str);
    }

    /**
     * 数组转换为字符串，主要用于把分隔符调整到第二个参数
     * @param  array $arr 要连接的数组
     * @param  string $glue 分割符
     * @return string
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public static function arr2str($arr, $glue = ',')
    {
        return implode($glue, $arr);
    }

    /**
     * @param string $filename dirpath&name
     */
    public static function createFile($filename)
    {
        if (!file_exists($filename)) {
            $fopen = fopen($filename, 'wb ');//新建文件命令
            fclose($fopen);
        }
    }

    /**
     * 获取文件列表
     * @param $dir
     * @return array
     */
    public static function listDir($dir)
    {
        $result = array();
        if (is_dir($dir)) {
            $file_dir = scandir($dir);
            foreach ($file_dir as $file) {
                if ($file == '.' || $file == '..') {
                    continue;
                } elseif (is_dir($dir . $file)) {
                    $result = array_merge($result, self::listDir($dir . $file . '/'));
                } else {
                    array_push($result, $dir . $file);
                }
            }
        }
        return $result;
    }

    public static function chmodr($path, $filemode)
    {
        if (!is_dir($path))
            return chmod($path, $filemode);
        $dh = opendir($path);
        while (($file = readdir($dh)) !== false) {
            if ($file != '.' && $file != '..') {
                $fullpath = $path . '/' . $file;
                if (is_link($fullpath))
                    return FALSE;
                elseif (!is_dir($fullpath) && !chmod($fullpath, $filemode))
                    return FALSE;
                elseif (!self::chmodr($fullpath, $filemode))
                    return FALSE;
            }
        }
        closedir($dh);
        if (chmod($path, $filemode))
            return TRUE;
        else
            return FALSE;
    }

    /**
     * 去空格
     * @param $str
     * @return mixed
     */
    public static function trimall($str)
    {
        $qian = array(" ", "　", "\t", "\n", "\r");
        return str_replace($qian, '', $str);
    }

    /**
     * 由身份证获取性别和出生年月日
     * @param $card
     * @return array
     */
    public static function getSexBirthFromIDCard($card)
    {

        $birth = substr($card, 6, 8);
        if (15 == strlen($card)) {
            $sex = substr($card, 15, 1) % 2 == 0 ? '女' : '男';
        } else {
            $sex = substr($card, 16, 1) % 2 == 0 ? '女' : '男';
        }
        return array(
            'birth' => $birth,
            'sex' => $sex
        );
    }

    /**
     * 字符串中是数组格式化为数组
     * @param $data
     * @return array
     */
    public static function formatArrStrToArr($data)
    {
        eval("\$data = " . $data . '; ');
        return $data;
    }

    /**
     * 验签  验证签名  基于sha1withRSA
     * @param $data 签名前的原字符串
     * @param $signature 签名串
     * @return bool
     * @link www.zh30.com
     */
    public static function verify($data, $signature)
    {
        $certs = array();
        openssl_pkcs12_read(file_get_contents("你的.pfx文件路径"), $certs, "password");
        if (!$certs) return;
        $result = (bool)openssl_verify($data, $signature, $certs['cert']); //openssl_verify验签成功返回1，失败0，错误返回-1
        return $result;
    }

    /**
     * 数组转xml
     * @param $arr
     * @param int $dom
     * @param int $item
     * @return string
     */
    public static function arrayToXml($arr, $root_name = 'root', $dom = 0, $item = 0, $version = "1.0", $unicode = "utf-8")
    {
        if (!$dom) {
            $dom = new \DOMDocument($version, $unicode);
        }
        if (!$item) {
            $item = $dom->createElement($root_name);
            $dom->appendChild($item);
        }
        foreach ($arr as $key => $val) {
            $itemx = $dom->createElement(is_string($key) ? $key : "item");
            $item->appendChild($itemx);
            if (!is_array($val)) {
                $text = $dom->createTextNode($val);
                $itemx->appendChild($text);

            } else {
                self::arrayToXml($val, $root_name, $dom, $itemx);
            }
        }
        return $dom->saveXML();
    }

    public static function arrayToXml1($arr, $root_name = null)
    {
        if ($root_name) {
            $xml = "<{$root_name}>";
        } else {
            $xml = '';
        };
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . self::arrayToXml1($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        if ($root_name) {
            $xml .= "</{$root_name}>";
        } else {
            $xml .= '';
        };
        return $xml;
    }

    /**
     * xml转数组
     * @param $xml
     * @return mixed
     */
    public static function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring), true);
        return $val;
    }

    /**
     * 上传base64文件
     * @param $base64
     * @return array|bool
     */
    public static function base64_upload($base64)
    {
        $base64_image = str_replace(' ', '+', $base64);
        //post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)) {
            //匹配成功
            if ($result[2] == 'jpeg') {
                $image_name = 'save.jpg';
                //纯粹是看jpeg不爽才替换的
            } else {
                $image_name = 'save.' . $result[2];
            }
            $image_file = $image_name;
            //服务器文件存储路径
            if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))) {
                return ['status' => 200, 'store_path' => $image_file];
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * RSA签名
     * @param $data 待签名数据(按照文档说明拼成的字符串)
     * @param $priKey商户私钥
     * return 签名结果
     */
    public static function rsaSign($data, $priKey)
    {
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        return $sign;
    }

    /**
     * RSA验签
     * @param mixed $data 待签名数据(如果是xml返回则数据为<plain>标签的值,包含<plain>标签，如果为form(key-value，一般指异步返回类的)返回,则需要按照文档中进行key的顺序进行，value拼接)
     * @param $ali_public_key_path 富友的公钥文件路径
     * @param $sign 要校对的的签名结果
     * return 验证结果
     */
    public static function rsaVerify($data, $pubKey, $sign, $ali_public_key_path = null)
    {
        if ($ali_public_key_path) $pubKey = file_get_contents($ali_public_key_path);
        $res = openssl_get_publickey($pubKey);
        $result = (bool)openssl_verify($data, base64_decode($sign), $res);
        openssl_free_key($res);
        return $result;
    }

    /**
     * RSA加密
     * @param $content
     * @param $public_key
     * return 加密后内容
     */
    public static function rsaEncrypt($content, $public_key){
        $pubKey = $public_key;
        $res = openssl_get_publickey($pubKey);
        //把需要加密的内容，按128位拆开解密
        $result  = '';
        for($i = 0; $i < strlen($content)/128; $i++  ) {
            $data = substr($content, $i * 128, 128);
            openssl_public_encrypt ($data, $encrypt, $res);
            $result .= $encrypt;
        }
        $result = base64_encode($result);
        openssl_free_key($res);
        return $result;
    }

    /**
     * RSA解密
     * @param $content 需要解密的内容，密文
     * @param $private_key 商户私钥文件路径
     * return 解密后内容，明文
     */
    public static function rsaDecrypt($content, $private_key) {
        $priKey = $private_key;
        $res = openssl_get_privatekey($priKey);
        //用base64将内容还原成二进制
        $content = base64_decode($content);
        //把需要解密的内容，按128位拆开解密
        $result  = '';
        for($i = 0; $i < strlen($content)/128; $i++  ) {
            $data = substr($content, $i * 128, 128);
            openssl_private_decrypt($data, $decrypt, $res);
            $result .= $decrypt;
        }
        openssl_free_key($res);
        return $result;
    }

    //$filePath是服务器的文件地址
    //$saveAsFileName是用户指定的下载后的文件名
    public function download1($filePath, $saveAsFileName = null)
    {

        if (!$saveAsFileName) {
            $saveAsFileName = basename($filePath);
        }
        // 清空缓冲区并关闭输出缓冲
        ob_end_clean();

        //r: 以只读方式打开，b: 强制使用二进制模式
        $fileHandle = fopen($filePath, "rb");
        if ($fileHandle === false) {
            echo "Can not find file: $filePath\n";
            exit;
        }

        Header("Content-type: application/octet-stream");
        Header("Content-Transfer-Encoding: binary");
        Header("Accept-Ranges: bytes");
        Header("Content-Length: " . filesize($filePath));
        Header("Content-Disposition: attachment; filename=\"$saveAsFileName\"");

        while (!feof($fileHandle)) {

            //从文件指针 handle 读取最多 length 个字节
            echo fread($fileHandle, 32768);
        }
        fclose($fileHandle);
    }

    public function download2($filepath)
    {
        set_time_limit(0);  //大文件在读取内容未结束时会被超时处理，导致下载文件不全。

        $fpath = $filepath;
        $file_pathinfo = pathinfo($fpath);
        $file_name = $file_pathinfo['basename'];
        $file_extension = $file_pathinfo['extension'];
        $handle = fopen($fpath, "rb");
        if (FALSE === $handle)
            exit("Failed to open the file");
        $filesize = filesize($fpath);

        header("Content-type:application/octet-stream");//更具不同的文件类型设置header输出类型
        header("Accept-Ranges:bytes");
        header("Accept-Length:" . $filesize);
        header("Content-Disposition: attachment; filename=" . $file_name);

        while (!feof($handle)) {
            $contents = fread($handle, 8192);
            echo $contents;
            @ob_flush();  //把数据从PHP的缓冲中释放出来
            flush();      //把被释放出来的数据发送到浏览器
        }
        fclose($handle);
        exit;
    }

    /**
     * 检测网络是否连接
     * @param $url
     * @return bool
     */
    public static function varifyUrl($url)
    {
        $check = @fopen($url, "r");
        if ($check) {
            $status = true;
        } else {
            $status = false;
        }
        return $status;
    }

    /**
     * tp系统加密方法
     * @param string $data 要加密的字符串
     * @param string $key  加密密钥
     * @param int $expire  过期时间 单位 秒
     * @return string
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public static function think_encrypt($data, $key = '', $expire = 0) {
        $key  = md5(empty($key) ? 'wodrow' : $key);
        $data = base64_encode($data);
        $x    = 0;
        $len  = strlen($data);
        $l    = strlen($key);
        $char = '';
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) $x = 0;
            $char .= substr($key, $x, 1);
            $x++;
        }
        $str = sprintf('%010d', $expire ? $expire + time():0);
        for ($i = 0; $i < $len; $i++) {
            $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
        }
        return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
    }
    /**
     * tp系统解密方法
     * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
     * @param  string $key  加密密钥
     * @return string
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public static function think_decrypt($data, $key = ''){
        $key    = md5(empty($key) ? 'wodrow' : $key);
        $data   = str_replace(array('-','_'),array('+','/'),$data);
        $mod4   = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        $data   = base64_decode($data);
        $expire = substr($data,0,10);
        $data   = substr($data,10);
        if($expire > 0 && $expire < time()) {
            return '';
        }
        $x      = 0;
        $len    = strlen($data);
        $l      = strlen($key);
        $char   = $str = '';
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) $x = 0;
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            }else{
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return base64_decode($str);
    }
    /**
     * 数据签名认证
     * @param  array  $data 被认证的数据
     * @return string       签名
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public static function data_auth_sign($data) {
        //数据类型检测
        if(!is_array($data)){
            $data = (array)$data;
        }
        ksort($data); //排序
        $code = http_build_query($data); //url编码并生成query字符串
        $sign = sha1($code); //生成签名
        return $sign;
    }


    /**
     * 阿拉伯数字金额转汉字大写
     *@param String Int $num 要转换的小写数字或小写字符串
     *@returnreturn 大写汉字
     *小数位为两位
     */
    public static function num_to_rmb($num){
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        //精确到分后面就不要了，所以只留两个小数位
        $num = round($num, 2);
        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大，请检查";
        }
        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num)-1, 1);
            } else {
                $n = $num % 10;
            }
            //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;
            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            //结束循环
            if ($num == 0) {
                break;
            }
        }
        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j-3;
                $slen = $slen-3;
            }
            $j = $j + 3;
        }
        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c)-3, 3) == '零') {
            $c = substr($c, 0, strlen($c)-3);
        }
        //将处理的汉字加上“整”
        if (empty($c)) {
            return "零元整";
        }else{
            return $c . "整";
        }
    }

    public static function UnicodeEncode($str){
        //split word
        preg_match_all('/./u',$str,$matches);

        $unicodeStr = "";
        foreach($matches[0] as $m){
            //拼接
            $unicodeStr .= "&#".base_convert(bin2hex(iconv('UTF-8',"UCS-4",$m)),16,10);
        }
        return $unicodeStr;
    }

    public static function unicodeDecode($unicode_str){
        $json = '{"str":"'.$unicode_str.'"}';
        $arr = json_decode($json,true);
        if(empty($arr)) return '';
        return $arr['str'];
    }

    public static function unicode2utf8($str)
    {
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches', 'return iconv("UCS-2BE","UTF-8",pack("H*", $matches[1]));'), $str);
    }
}